import React, { Component } from 'react';
import {Redirect} from 'react-router-dom'

// 导入models
import models from '@/models/common'

function CheckLogin(Cmp) {
	
	return class Hoc extends Component {

		state = {
			// 是否存在jwt
			isFinish: false,
			// 是否登录
			isLogin:false
		}

		render() {
			return (
				<>
					{this.state.isFinish ? this.state.isLogin ? <Cmp {...this.props}/> : <Redirect to="/login"/> : <></> }
				</>
			);
		}
		// jwt验证
		componentDidMount() {
			// 判断是否存在jwt
			let jwt = localStorage.getItem('jwt');
			if (jwt) {
				models.jwtPreCheck().then(ret => {
					// 修改状态为true，加载<Cmp />页面
					if (ret.errNo === 0) {
						this.setState(() => {
							return {
								isLogin:true,
								isFinish: true,
							}
						})
					} else {
						// 有jwt，但验证失败
						this.setState(() => {
							return {
								isLogin: false,
								isFinish: true,
							}
						});
					}
				})
			} else {
				this.setState(() => {
					return {
						isFinish: true
					}
				});
			}
		}
	}
}

export default CheckLogin;
